<?php


namespace App\Models;


class LessonPage extends Model
{
    protected $table = 'lesson_pages';


    const BOOK_PAGE = 1;

    // ============= scope ==========
    public function scopeOfType($query, $type)
    {
        return $query->where('type', $type);
    }

    // ============= field ==========
    public function setType($type)
    {
        $this->type = $type;
    }

    public function getType()
    {
        return $this->type;
    }

    public function setLessonId($lessonId)
    {
        $this->lesson_id = $lessonId;
    }

    public function setContent($content)
    {
        $this->content = json_encode($content);
    }

    public function getContent()
    {
        return json_decode($this->content, true);
    }

    public function getName()
    {
        return $this->name;
    }

    public function setName($name)
    {
        $this->name = $name;
    }

    public function setSequence($sequence)
    {
        $this->sequence = $sequence;
    }

    // ============= logic ==========
    public static function parseKnowledge($lessonId)
    {
        $pages = static::where(['lesson_id'=>$lessonId])->ofType(static::BOOK_PAGE)->get();
        $knowledgeIds = [];
        $assistWordIds = [];
        foreach ($pages as $page) {
            if (!empty($page['content']) && $page['content'] != 'null') {
                $sentences = json_decode($page['content'], true);
                if (!empty($sentences['sentences'])) {
                    foreach ($sentences['sentences'] as $sentence) {
                        foreach ($sentence['words'] as $word) {
                            if (!empty($word['knowledgeId'])) {
                                // 知识点的单词才加入到学单词环节
                                $knowledgeIds[] = $word['knowledgeId'];
                            } elseif (!empty($word['assistId'])) {
                                $assistWordIds[] = $word['assistId'];
                            }
                        }
                    }
                }
            }
        }
        /** @var Lesson $lessonObj */
        $lessonObj = Lesson::find($lessonId);
        if ($knowledgeIds) {
            $lessonObj->knowledge()->sync($knowledgeIds);
        }
        if ($assistWordIds) {
            $lessonObj->assistWord()->sync($knowledgeIds);
        }
    }

}
